import { reqLogin, reqLogout } from '@/api/user'

const state = {
  token: localStorage.getItem('token') || '',
  name: localStorage.getItem('name') || '',
}
const getters = {}
const actions = {
  async login({ commit }, { phone, password }) {
    const user = await reqLogin(phone, password)
    commit('LOGIN', user)
    localStorage.setItem('token', user.token)
    localStorage.setItem('name', user.name)
  },
  async logout({ commit }) {
    await reqLogout()
    commit('LOGOUT')
    localStorage.removeItem('token')
    localStorage.removeItem('name')
  },
}
const mutations = {
  LOGIN(state, user) {
    state.token = user.token
    state.name = user.name
  },
  LOGOUT(state) {
    state.token = ''
    state.name = ''
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
}
